<template>
    <div class="h-full overflow-hidden flex flex-col">
        <div class="flex-1 overflow-auto pt-[26px] pb-[80px] px-[56px]">
            <div class="flex flex-row items-center gap-[10px]">
                <div class="bg-theme w-1 h-5 rounded-xs"></div>
                <span class="text-theme text-[18px] font-bold">公司相册</span>
            </div>
            <section class="bg-[#F5F7FA] rounded-sm box-border p-4 mt-3 2xl:w-[750px]">
                <p class="text-sm text-primary">上传公司相册有什么用？</p>
                <p class="text-sm text-secondary mt-2">丰富的公司环境图片、团建活动图片等可以让牛人直观感受公司氛围，有效吸引牛人。(最多可上传20张)</p>
            </section>
            <section class="mt-6 2xl:w-[750px]">
                <div class="flex flex-row items-center justify-between">
                    <div class="text-primary text-base font-medium">相册列表</div>
                    <div style="margin-left: auto; margin-inline-end: 16px;" class="text-primary text-sm flex flex-row items-center gap-1 cursor-pointer">
                        自定义排序
                        <GpFontIcon name="icon-yiwen1" class="text-[#ACAEB2]"/>
                    </div>
                    <a-switch v-model:checked="formState.sortEnabled" />
                </div>
                <VueDraggable v-model="formState.albumes" filter=".action-trigger" :disabled="!formState.sortEnabled" :animation="150" class="flex flex-row flex-wrap gap-3 mt-3">
                    <div class="relative rounded-sm cursor-pointer overflow-hidden group" 
                        style="width: 180px; height: 135px;"
                        v-for="(item, index) in formState.albumes" :key="item.url"
                    >
                        <img :src="item.url" width="100%" height="100%" class="size-full object-cover block" />
                        <div class="hidden group-hover:flex absolute inset-0 bg-black/60 flex-row gap-12 justify-center items-center">
                            <div @click="handleReplace(index)" class="flex flex-col justify-center items-center text-white touchable-opacity">
                                <GpFontIcon name="icon-zhongxinshangchuan" class="!text-2xl !leading-none" />
                                <span class="text-sm">更换</span>
                            </div>
                            <div @click="handleRemove(item)" class="flex flex-col justify-center items-center text-white touchable-opacity">
                                <GpFontIcon name="icon-shanchu2" class="!text-2xl !leading-none" />
                                <span class="text-sm">删除</span>
                            </div>
                        </div>
                    </div>
                    <div class="action-trigger flex flex-col justify-center items-center border border-dashed border-[#CED4DB] bg-[#FCFBFF] cursor-pointer overflow-hidden rounded-sm hover:border-theme" 
                        :class="uploading ? 'cursor-not-allowed' : ''"
                        style="width: 180px; height: 135px;"
                        @click="uploadAction()"
                    >
                        <GpFontIcon name="icon-shangchuan" class="!text-[40px] text-[#ced4db] !leading-none"/> 
                        <span class="text-secondary text-sm mt-1">添加公司照片</span>
                        <span class="text-[#ACAEB2] text-xs mt-[2px]">图片大小不超过4M</span>
                    </div>
                </VueDraggable>
            </section>
        </div>
        <div class="px-[56px] box-border h-[88px] border-t border-solid border-t-[#EEEEEE] relative">
            <div class="flex flex-row justify-end items-center h-full 2xl:w-[750px]">
                <a-button type="primary" class="rounded-sm w-[124px]" size="large" :loading="uploading || formLoading" @click="handleSubmit()">
                    保存
                </a-button>
            </div>
            <div class="text-[#ACAEB2] text-sm flex flex-row items-center gap-1 cursor-pointer absolute left-[56px] top-[34px]">
                上传注意事项
                <GpFontIcon name="icon-yiwen1"/>
            </div>
        </div>
    </div>
</template>
<script lang="ts" setup>
import { postCompanyinfoPictures } from '@/api/siderBar/companyInfo';
import type { CompanyInfoResult, CompanyPictureRequest } from '@/api/siderBar/model';
import { message } from 'ant-design-vue';
import {
  VueDraggable
} from 'vue-draggable-plus'
defineOptions({
    name: "CompanyAlbum"
})
type Props = Partial<CompanyInfoResult>
const props = defineProps<Props>()
const emit = defineEmits<{
    refresh: []
}>()
type FormState = {
    albumes: CompanyPictureRequest[]
    sortEnabled: boolean
};
const formLoading = ref(false)
const formState = ref<FormState>(getInitialState())
const replaceIndex = ref<number>()
const {
    uploading,
    uploadAction
} = useUpload({
    type: "image",
    multipleOrOpts: true,
    beforeUpload(files) {
        const sizeValid =  files.every(file => sizeLimit(file.size, 4))
        if (!sizeValid) {
            message.error('上传文件大小不超过4M')
            return false
        }
    },
    receiveResults(result) {
        if (result.length > 0) {
            console.log(replaceIndex.value)
            if (isSetValue(replaceIndex.value)) {
                formState.value.albumes[replaceIndex.value] = {
                    url: result[0].fullName
                }
            } else {
                result.forEach(r => {
                    formState.value.albumes.push({
                        url: r.fullName
                    })
                })
            }
        }
    },
    finallyHandler() {
        replaceIndex.value = void 0;
    },
})
function getInitialState(): FormState {
    return {
        albumes: [],
        sortEnabled: false
    }
}
watch(() => props.pictures, () => {
    if (props.pictures) {
        populate()
    }
}, {
    immediate: true
})
function populate() {
    if (props.pictures) {
        formState.value.albumes.length = 0
        formState.value.albumes.push(...props.pictures)
    }
}
async function handleSubmit() {
    try {
        formLoading.value = true
        await postCompanyinfoPictures(formState.value.albumes)
        formLoading.value = false
        message.success('保存成功')
        emit("refresh")
    } catch (error) {
        formLoading.value = false
    }
}
function handleReplace(index: number) {
    replaceIndex.value = index
    uploadAction({
        multipleOrOpts: false
    })
}
function handleRemove(item: CompanyPictureRequest) {
    removeItem(formState.value.albumes, l => l.url === item.url)
}
</script>